package com.imeth.base.interceptor;

import com.imeth.base.util.StringUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URL;
import java.util.List;

public class AccessKeyInterceptor extends HandlerInterceptorAdapter {

	private List<String> defaultAccessAllowedFrom;
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		String referer = request.getHeader("Referer");

		if(StringUtils.isEmpty(referer)) {
			return true;
		}

		URL u = new URL(referer);
		String host = u.getHost().toLowerCase();

		for(String s : defaultAccessAllowedFrom) {
			if(host.matches(s)){							
				response.setHeader("Access-Control-Allow-Origin", "*");
				break;
			}
		}
		return true;
	}

	public List<String> getDefaultAccessAllowedFrom() {
		return defaultAccessAllowedFrom;
	}

	public void setDefaultAccessAllowedFrom(List<String> defaultAccessAllowedFrom) {
		this.defaultAccessAllowedFrom = defaultAccessAllowedFrom;
	}
}